package com.example.demo.information.controller;

import com.alibaba.fastjson.JSON;
import com.example.demo.account.entity.SysUserRole;
import com.example.demo.account.service.UserService;
import com.example.demo.common.utils.Constant;
import com.example.demo.common.utils.SpringSecurityUtils;
import com.example.demo.information.entity.Bjxx;
import com.example.demo.information.entity.School;
import com.example.demo.information.entity.Student;
import com.example.demo.information.entity.info.StudentInfo;
import com.example.demo.information.service.BjxxService;
import com.example.demo.information.service.SchoolService;
import com.example.demo.information.service.StudentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;
    @Autowired
    private SchoolService schoolService;
    @Autowired
    private UserService userService;
    @Autowired
    private BjxxService bjxxService;


    @RequestMapping("/toStudent")
    private String toStudentList(){
        return "information/student/studentList";
    }

    /**
     * 加载学生列表
     * @param searchVal 查询内容
     * @param page 页码
     * @param limit 每页个数
     * @param id 索引树id
     * @param type 索引的类型
     * @return
     */
    @RequestMapping("/studentList")
    @ResponseBody
    private Map<String,Object> studentList(String searchVal,Integer page,Integer limit,Long id ,String type){
        Map<String,Object> map = new HashMap<>();
        List<Student> studentList = studentService.findByTypeAndSearch(searchVal,id,type);
        studentList = studentService.findByRoleForStudentList(studentList);
        int count = studentList.size();
        studentList = studentService.getCurrPageByStuList(studentList,page,limit);
        List<StudentInfo> stuInfoList = new LinkedList<>();
        for(Student stu:studentList){
            stuInfoList.add(new StudentInfo(stu));
        }
        map.put("data",stuInfoList);
        map.put("code",0);
        map.put("msg","");
        map.put("count",count);
        return map;
    }

    @RequestMapping("/toStudentAdd")
    private String toStudentAdd(ModelMap map){
        List<School> list = schoolService.getCurrRoleSchoolList();
        map.addAttribute("xxList", list);
        return "information/student/studentAdd";
    }

    @RequestMapping("/studentAdd")
    @ResponseBody
    private String studentAdd(StudentInfo studentInfo){
        System.out.println(studentInfo.toString());
        if(studentInfo.getBjxxId()==null||studentInfo.getXxxxId()==null
                ||StringUtils.isBlank(studentInfo.getName())||StringUtils.isBlank(studentInfo.getSfz())){
            return "学生信息未填写完整。";
        }
        try{
            if(studentInfo.getXsId()!=null){
                School school = schoolService.findById(studentInfo.getXxxxId());
                Bjxx bjxx = bjxxService.findById(studentInfo.getBjxxId());
                Student stu = studentService.findById(studentInfo.getXsId());
                stu.setSchool(school);
                stu.setBjxx(bjxx);
                if(!stu.getSfz().equals(studentInfo.getSfz())
                        ||!stu.getXjfh().equals(studentInfo.getXjfh())){
                    List<Student> list = studentService.findBySfzOrXjfh(studentInfo.getSfz(),studentInfo.getXjfh());
                    if(list!=null&&list.size()>1
                            ||list.get(0).getId()!=stu.getId()){
                       return "存在身份证或学籍辅号相同的其他学生。";
                    }
                    if(!stu.getSfz().equals(studentInfo.getSfz())){
                        userService.deleteXsAuth(stu);
                    }
                }
                stu.setName(studentInfo.getName());
                stu.setSfz(studentInfo.getSfz());
                stu.setXjfh(studentInfo.getXjfh());
                stu.setSex(studentInfo.getSex());
                userService.createUserForStu(stu);
                studentService.save(stu);
                return "success";
            }else{
                School school = schoolService.findById(studentInfo.getXxxxId());
                Bjxx bjxx = bjxxService.findById(studentInfo.getBjxxId());
                Student temp = new Student(studentInfo);
                temp.setSchool(school);
                if(studentService.checkStudent(studentInfo.getSfz(),studentInfo.getXjfh())){
                    return "存在身份证或学籍辅号相同学生。";
                }
                userService.createUserForStu(temp);
                String message = studentService.saveStuInfo(studentInfo,school,bjxx);
                return Constant.SUCCESS.equals(message)?"success":message;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }

    @RequestMapping(value = "/studentDel")
    @ResponseBody
    private String studentDel(@RequestParam("xsId")String xsId){
        //TODO 删除学生之前可能要判断是否有拍过照片，防止误删除；删除学生还要把账号删除了。
        String[] idArr = xsId.split(",");
        try{
            for(String id : idArr){
                Student student = studentService.findById(Long.valueOf(id));
                //studentService.deleteById(Long.valueOf(id));
                userService.deleteXsAuth(student);
                studentService.deleteById(student.getId());
            }
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }

    @RequestMapping(value = "/toStudentExp")
    private String toStudentExp(){
        return "information/student/studentExp";
    }

    @RequestMapping("/stuDownFile")
    private void stuDownFile(HttpServletResponse response){
        SysUserRole currSysUserRole = SpringSecurityUtils.getCurrentUserDetails().getCurrSysUserRole();
        if(Constant.XX_USER_ID.equals(currSysUserRole.getRole_id())){
            studentService.createDownFileStuExpForXXAdmin(response);
        }else{
            studentService.createDownFile(response);
        }
    }

    /**
     * 该方法用于先返回页面JSON,页面再返回JSON
     * @param file
     * @return
     */
    @RequestMapping("/stuExpFile")
    @ResponseBody
    private String stuExpFile(MultipartFile file){
        //TODO 上传学生数据
        System.out.println("我来上传了.");
        String message = "error";
        int code = 0;
        if (null != file) {
            /*String myFileName = file.getOriginalFilename();// 文件原名称
            String fileName = BasePath.getImgPath("yyyyMMddHHmmss")+
                    Integer.toHexString(new Random().nextInt()) +"."+ myFileName.
                    substring(myFileName.lastIndexOf(".") + 1);
            String pat=FileProperties.getFilePath()+"/src/main/webapp/";//获取文件保存路径
            String sqlPath="static/images/upload/storeHead/"+BasePath.getImgPath("yyyyMMdd")+"/";

            File fileDir=new File(pat+sqlPath);
            if (!fileDir.exists()) { //如果不存在 则创建
                fileDir.mkdirs();
            }
            String path=pat+sqlPath+fileName;
            File localFile = new File(path);
            try {
                file.transferTo(localFile);
                //return sqlPath+fileName;
                message = "success";
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }*/
        }else{
            code = 1;
            message = "文件为空";
        }
        Map<String,Object> map = new HashMap<>();
        map.put("data","");
        map.put("code",code);
        map.put("msg",message);
        return JSON.toJSONString(map);//直接返回map也可行
    }

    /**
     * 该方法用于先直接导入文件+导入对象
     * @param file
     * @return
     */
//    @RequestMapping("/stuExpFileAndDr")
//    @ResponseBody
    private String stuExpFile2(MultipartFile file){
        String message = "error";int code = 0;
        Map<String,School> schoolMap = new HashMap<>();
        Map<Long,Map<String ,Bjxx>> xxbjMap = new HashMap<>();
        List<Student> studentList = new ArrayList<>();
        schoolMap = schoolService.getSchoolMap();
        xxbjMap = schoolService.getXXBjxxMap();
        try{
            studentList = studentService.getStuFromExpFile(file,schoolMap,xxbjMap);
        } catch (Exception e) {
            e.printStackTrace();
            message = "表格导入异常，检查下表格重新导入。";
            Map<String,Object> map = new HashMap<>();
            map.put("data","");
            map.put("code",1);
            map.put("msg",message);
            return JSON.toJSONString(map);//直接返回map也可行
        }
        int count=0,fail=0;
        for(Student student :studentList){
            if(studentService.checkStudent(student)){
                try{
                    userService.createUserForStu(student);
                    message = studentService.saveStuAndCheck(student);
                    if(Constant.SUCCESS.equals(message)){
                        count++;
                    }else{
                        fail++;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    fail++;continue;
                }
            }else{
                fail++;
            }
        }
        message = "成功导入"+count+";为导入"+fail;
        Map<String,Object> map = new HashMap<>();
        map.put("data","");
        map.put("code",code);
        map.put("msg",message);
        return JSON.toJSONString(map);//直接返回map也可行
    }
    /**
     * 该方法用于先直接导入文件+导入对象+创建对应班级
     * @param file
     * @return
     */
    @RequestMapping("/stuExpFileAndDr")
    @ResponseBody
    private String stuExpFile3(MultipartFile file){
        Map<String,Object> paramMap;//导入信息时返回map
        Map<String,Object> tabdataMap = new HashMap<>();//导入学生的返回信息
        String message = "error";int code = 0;
        Map<String,Object> map = new HashMap<>();
        map.put("data","");
        Map<String,School> schoolMap = schoolService.getSchoolMap();
        List<Student> studentList;
        try{
            paramMap = studentService.getStuAndBjxxFromExpFile(file,schoolMap);
        } catch (Exception e) {
            e.printStackTrace();
            message = "表格导入异常，检查下表格重新导入。";
            map.put("code",code);
            map.put("msg",message);
            return JSON.toJSONString(map);//直接返回map也可行
        }
        studentList = (List<Student>) paramMap.get("studentList");
        List<String> xxbjmcList = (List<String>) paramMap.get("bjmcList");
        Map<Long,School> xxMap = (Map<Long, School>) paramMap.get("xxMap");
        tabdataMap = (Map<String, Object>) paramMap.get("tabdataMap");
        bjxxService.createBjxxByXxbjmcList(xxbjmcList,xxMap);//创建新的班级
        Map<Long,Map<String ,Bjxx>> xxbjMap = schoolService.getXXBjxxMap();
        int count=0,fail=0;
        for(Student student :studentList){
            String xxbjmc = student.getXxbjmc();
            xxbjmc = xxbjmc.lastIndexOf("@@")!=-1?xxbjmc.split("@@")[1]:xxbjmc;
            Bjxx bjxx = student.getSchool()!=null&&xxbjMap.containsKey(student.getSchool().getId())
                    ?xxbjMap.get(student.getSchool().getId()).get(xxbjmc):null;
            if(bjxx!=null){student.setBjxx(bjxx);}

            Map<String,Object> temp = (Map<String, Object>) tabdataMap.get(student.getErrMsg());
            if(studentService.checkStudent(student)){
                try{
                    userService.createUserForStu(student);
                    message = studentService.saveStuAndCheck(student);
                    if(Constant.SUCCESS.equals(message)){
                        temp.put("errMsg","保存成功");
                        count++;
                    }else{
                        temp.put("errMsg",message);
                        fail++;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    temp.put("errMsg","保存失败");
                    fail++;continue;
                }
            }else{
                temp.put("errMsg","学生信息不完全");
                fail++;
            }
        }
        message = "成功导入"+count+";未导入"+fail;
        map.put("code",code);
        map.put("msg",message);
        map.put("tabdata",tabdataMap);
        System.out.println(tabdataMap);
        return JSON.toJSONString(map);//直接返回map也可行
    }



    /**
     * @Title: uploadExcelFile
     * @Description: 上传excel文件
     * @return
     * @throws Exception String
     */
    /*public String uploadExcelFile() throws Exception {

        List<String> extList = Constants.FILETYPEMAP.get(fileExt);
        boolean correctFileFlag = isCorrectFileType(file, extList);
        if(!correctFileFlag){
            FileUtils.deleteQuietly(file);
            Struts2Utils.renderText("错误:文件类型错误，请选择正确的文件："+extList);
            return null; //这里不需要页面转向，所以返回空就可以了
        }

        String extName = "";//扩展名
        String newFileName= "";//新文件名
        String nowTime = SysUtil.md5(String.valueOf(System.currentTimeMillis()));
        String savePath = ServletActionContext.getRequest().getRealPath("");
        savePath = savePath +File.separator+Constants.UPLOADTMP+File.separator;
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setCharacterEncoding("utf-8");
        //获取扩展名
        extName = FilenameUtils.getExtension(fileFileName);
        newFileName = nowTime+"."+extName;
        File newFile = new File(savePath+newFileName);

        String tempFilePath = ServletActionContext.getRequest().getRealPath("");

        tempFilePath += File.separator+"temp"+File.separator;
        File tempFile = new File(tempFilePath+newFileName);
        file.renameTo(tempFile);

        FileUtils.copyFile(tempFile, newFile);
        FileUtils.deleteQuietly(tempFile);

        //file.renameTo(newFile);

        if(tocsv ==0){
            Struts2Utils.renderText(fileFileName+"|"+newFileName);
        }
        //如果要转换成csv文件，则返回转换后的csv文件名
        else if(tocsv == 1){
            nowTime = SysUtil.md5(String.valueOf(System.currentTimeMillis()));
            String csvFile = savePath+nowTime+".csv";
            if(extName.equalsIgnoreCase("xls")){
                Xls2csv xls2csv = new Xls2csv(savePath+newFileName,csvFile);
                xls2csv.process();
            }
            else if(extName.equalsIgnoreCase("xlsx")){
                Xlsx2csv xlsx2csv = new Xlsx2csv(savePath+newFileName,csvFile);
                xlsx2csv.process();
            }
            newFile.deleteOnExit();
            Struts2Utils.renderText(nowTime+".csv");
        }

        return null; //这里不需要页面转向，所以返回空就可以了
    }*/



}
